//
//  ViewController.swift
//  demo
//
//  Created by chengbifeng on 2020/11/26.
//

import UIKit
import WebKit
class ViewController: UIViewController,WKUIDelegate {

    var webView: WKWebView!
    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let myURL = URL(string:"https://bishengoffice.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)

        webView.allowsBackForwardNavigationGestures = true
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "back", style: .plain, target: self, action: #selector(backBtn(sender:)))
        navigationItem.title = "初始化中..."
    }

    @objc func backBtn(sender: UIBarButtonItem) {
        if self.webView.canGoBack {
            self.webView.goBack()
        } else {
            print("Cannot go backwards.")
        }
    }
    
    @objc func openTapped(sender: UIBarButtonItem) {
        let ac = UIAlertController(title: "Open page...", message: nil, preferredStyle: .actionSheet)
        ac.addAction(UIAlertAction(title: "apple.com", style: .default, handler: openPage))
        ac.addAction(UIAlertAction(title: "hackingwithswift.com", style: .default, handler: openPage))
        ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        present(ac, animated: true, completion: nil)

    }
    
    func openPage(action: UIAlertAction!) {
        let url = NSURL(string: "https://" + action.title!)!
        webView.load(NSURLRequest(url: url as URL) as URLRequest)
    }
}

extension ViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        if navigationAction.targetFrame == nil {
            webView.load(navigationAction.request)
        }
        return nil
    }
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if let title = webView.title {
            navigationItem.title = title
        }
    }
}
